﻿using System;
using System.Collections.Generic;
using System.Text;
using FeedDotNet.Common;

namespace ConsoleApplication
{
    class IMDbPopulator
    {
        private IMDbDictionary imdbDictionary;
        public IMDbPopulator(IMDbDictionary dict)
        {
            imdbDictionary = dict;
        }

        internal Feed FillFeedWithIMDbData(Feed mergedFeeds)
        {
            List<string> titles = new List<string>();

            Feed newFeed = new Feed(mergedFeeds);

            foreach (FeedItem item in mergedFeeds.Items)
            {
                titles.Add(item.Title);
            }

            Dictionary<string, List<IMDbDictionary.Movie>> movies = imdbDictionary.GetMoviePlotsByTitle(titles);

            foreach (FeedItem item in newFeed.Items)
            {
                List<IMDbDictionary.Movie> possibleMovies;
                if (movies.TryGetValue(item.Title, out possibleMovies))
                {
                    if (possibleMovies.Count > 1)
                    {
                        StringBuilder plots = new StringBuilder();
                        foreach (IMDbDictionary.Movie movie in possibleMovies)
                        {
                            plots.Append(movie.Title);
                            plots.Append("<hr/>");
                            plots.Append(movie.Plot);
                            plots.Append("<hr/><br/>");
                        }
                        item.Summary = plots.ToString();
                    }
                    else
                    {
                        item.Summary = possibleMovies[0].Plot;
                    }
                }
            }

            return newFeed;
        }
    }
}
